<template>
  <view class="cashgift_pop_box">
    <unipopup ref="unipopup" type="center" :show="showCashgift" class="cashgift_pop">
      <text class="close_icon iconfont icon-guanbi" @click="close"></text>
      <view class="cashgift_content">
        <view class="title"><text class="iconfont icon-wenhao" @click="showHelp"></text>生成礼金</view>
        <form @submit="submit" :report-submit="true">
          <view class="form_item">
            <text class="label">积分余额：</text>
            <text class="text">{{userInfo.gold}}</text>
          </view>
          <view class="form_item">
            <text class="label">商品名：</text>
            <text class="text">{{itemDetail.title}}</text>
          </view>
          <view class="form_item">
            <text class="label">礼金金额：</text>
            <view class="text">
              <input type="digit" class="input" v-model="cashgiftForm.rightsPrice" placeholder="下单时抵扣,最低1元" />
            </view>
          </view>
          <view class="form_item">
            <text class="label">消耗积分：</text>
            <text class="text">{{parseInt(cashgiftForm.rightsPrice * 10)}}</text>
          </view>
          <view class="form_item">
            <text class="label">过期时间：</text>
            <view class="text">
              <picker mode="date" :value="cashgiftForm.rightsEndTime" :start="formatDate(new Date())" :end="formatDate(Date.now() + 7 * 24 * 3600 * 1000)"
                @change="bindTimeChange">
                <input type="text" disabled class="input" :value="cashgiftForm.rightsEndTime" placeholder="点我选择" />
              </picker>
            </view>
          </view>
          <view class="btn_group">
            <button class="btn cancel" @click="close">取消</button>
            <button class="btn submit" form-type="submit">生成</button>
          </view>
        </form>
      </view>
    </unipopup>
    <!-- 消息弹框 -->
    <message ref="message"/>
  </view>
</template>

<script>
  import CONFIG from '@/config/config.conf'
  import unipopup from "@/pages/pagecomponents/uni/uni-popup.vue"
  export default {
    components: {
      unipopup
    },
    props: {
      itemDetail: {
        type: Object,
      },
    },
    data() {
      return {
        cashgiftForm: {
          rightsPrice: '',
          rightsEndTime: '', // 默认当前时间
        },
        showCashgift: false,
      }
    },
    computed:{
      userInfo(){
        return this.$store.state.userInfo
      },
    },
    created() {
    },
    methods: {
      submit(e) {
        let formId = e.detail.formId // formId，用于发送模板消息
        // 提交表单
        let cashgiftForm = this.cashgiftForm
        let userInfo = this.userInfo
        let itemDetail = this.itemDetail
        let hasNull = false;
        Object.keys(cashgiftForm).some(item => {
          if (!cashgiftForm[item] || cashgiftForm[item] === '') {
            hasNull = true;
            return true;
          }
        })
        if (hasNull) {
          this.$refs.unipopup.shake(); // 模态框抖动
          uni.showToast({
            icon: 'none',
            title: '对不起，请将表单填写完整后提交'
          });
          return;
        } else if (!/^(([1-9][0-9]*)|(([1]\.\d{1}|[1-9][0-9]*\.\d{1})))$/.test(Number(cashgiftForm.rightsPrice))) {
          this.$refs.unipopup.shake(); // 模态框抖动
          uni.showToast({
            icon: 'none',
            title: '对不起，礼金金额最低为1元，且仅支持1位小数'
          });
          return;
        } else if (Number(cashgiftForm.rightsPrice * 10) > userInfo.gold) {
          this.$refs.unipopup.shake(); // 模态框抖动
          uni.showToast({
            icon: 'none',
            title: '对不起，礼金金额不可高于您的积分余额'
          });
          return;
        }
        
        let data = {
          formId: formId, // 表单id用于发送模板消息
          page: '/pagecomponents/cashgift/index', // 点击模板跳转的页面
          rightsName: `${CONFIG.appNameC}礼金`, // 淘礼金名称
          rightsNumber: 1, // 淘礼金总个数,当前1
          tId: itemDetail.id,
          goodsId: itemDetail.goodsId,
          mainPic: itemDetail.mainPic,
          dtitle: itemDetail.title,
          rightsEndTimeMode: 2, //结束日期的模式,1:相对时间，2:绝对时间
          status: 1, //淘礼金状态：1已创建2已使用3已过期4已注销
          ...cashgiftForm, // 表单数据
        }
        this.$refs['message'].showLoading() // 提示加载中弹框
        this.$api.user.createCashgift(data).then(res => { // 创建淘礼金
          this.$refs['message'].hideLoading() // 隐藏加载中弹框
          // 调用刷新用户信息方法
          this.$store.commit('refreshUserInfo')
          uni.showModal({
            showCancel: false,
            confirmText: '我知道了',
            title: '成功',
            content: '恭喜，礼金创建成功，已为您复制到剪贴板，后续可在“我的-礼金”中查看',
            success: res => {}
          });
          this.close();
          // #ifndef H5
          uni.setClipboardData({
            data: res.data,
            success: function() {
              uni.hideToast(); // 隐藏默认提示框
            }
          });
          // #endif
          // #ifdef H5
          const btn = document.querySelector('.copy_tkl');
          const input = document.createElement('input');
          input.setAttribute('readonly', 'readonly');
          input.setAttribute('value', res.data);
          document.body.appendChild(input);
          input.select();
          input.setSelectionRange(0, 9999);
          if (document.execCommand('copy')) {
            document.execCommand('copy');
            uni.showModal({
              content: res.data,
              showCancel: false
            });
          }
          document.body.removeChild(input);
          // #endif
        }).catch(err => {
          this.$refs['message'].hideLoading() // 隐藏加载中弹框
        })
      },
      showHelp() {
        uni.showModal({
          title: '教程',
          confirmText: '我知道了',
          content: '【礼金是什么】礼金是您消耗积分生成的,可叠加优惠券使用的,无门槛红包\r\n【礼金过期】如果超过有效期未使用,第二天系统会自动返还您消耗的积分\r\n【积分怎么来】每日签到，或在订单列表绑定单号后在小程序内下单皆可获得积分',
          showCancel: false,
        });
      },
      bindTimeChange(e) {
        this.cashgiftForm.rightsEndTime = e.target.value
      },
      close() {
        this.$emit('close')
        this.showCashgift = false
      },
      show() {
        this.showCashgift = true
      },
    }
  }
</script>

<style scoped lang="scss">
  .cashgift_pop_box {
    .cashgift_pop {
      .close_icon {
        position: absolute;
        top: 20upx;
        right: 20upx;
        font-size: 50upx;
      }
      .cashgift_content {
        padding: 50upx 0 0;
        width: 650upx;
        border-radius: 20upx;
        background-color: #ffffff;
        .title {
          text-align: center;
          padding: 0 50upx 50upx;
          color: #294d7d;
          font-size: 40upx;
          font-weight: 600;
          .iconfont {
            margin-right: 10upx;
            color: red;
            font-size: 40upx;
            font-weight: 600;
          }
        }
        .form_item {
          padding: 0 30upx;
          line-height: 70upx;
          font-size: 30upx;
          .label {
            display: inline-block;
            width: 150upx;
            height: 70upx;
            vertical-align: middle;
          }
          .text {
            display: inline-block;
            width: 400upx;
            height: 70upx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            vertical-align: middle;
            .input {
              height: 70upx;
              line-height: 70upx;
              border-bottom: 1px solid #C8C8C8;
            }
          }
        }
        .btn_group {
          height: 100upx;
          margin-top: 50upx;
          .btn {
            height: 100upx;
            display: inline-block;
            width: 50%;
            background: white;
          }
          .submit {
            color: white;
            background: #294d7d;
          }
        }
      }
    }
  }
</style>
